package com.jmgd.cjlx.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;

/**
 *
 * 接口请求DEMO
 * @author lyb
 *
 */
public class EncryptionUtils {
    /**
     * 生成签名值，用于验参
     * @param param 请求参数content
     * @param timestamp 请求参数时间戳
     * @param appSecret 应用秘钥
     * @return 签名值
     * @throws Exception 异常
     */
    public static String sign(String param, String timestamp, String appSecret) throws Exception {
        String signText = sha256Hex(param);
        byte[] secretSigning = hmac256(appSecret.getBytes("UTF-8"), timestamp);
        return DatatypeConverter.printHexBinary(hmac256(secretSigning, signText)).toLowerCase();
    }

    public static String sha256Hex(String s) throws Exception{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] d = md.digest(s.getBytes("UTF-8"));
        return DatatypeConverter.printHexBinary(d).toLowerCase();
    }

    public static byte[] hmac256(byte[] key, String msg) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
        mac.init(secretKeySpec);
        return mac.doFinal(msg.getBytes("UTF-8"));
    }
}
